import { loadEnv, defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
// import { createStyleImportPlugin, VantResolve } from "vite-plugin-style-import";
import viteCompression from "vite-plugin-compression";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import Components from "unplugin-vue-components/vite";
import path from "path";
import AutoImport from "unplugin-auto-import/vite";
import VueSetupExtend from "vite-plugin-vue-setup-extend";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import resolveExternalsPlugin from "vite-plugin-resolve-externals";
import Markdown from "vite-plugin-md";
import { prismjsPlugin } from "vite-plugin-prismjs";
import MarkdownItAnchor from "markdown-it-anchor";

// import postCssPxToRem from "postcss-pxtorem";

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  // 获取环境配置文件
  const env = loadEnv(mode, process.cwd());
  const { VITE_APP_ENV, VITE_APP_PUBLIC_PATH } = env;
  return {
    base: VITE_APP_ENV === "production" ? VITE_APP_PUBLIC_PATH : "/",
    plugins: [
      vue({ include: [/\.vue$/, /\.md$/] }),
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [path.resolve(process.cwd(), "src/assets/icons/svg")],
        // 指定symbolId格式
        symbolId: "icon-[dir]-[name]",
      }),
      /* createStyleImportPlugin({
                    resolves: [VantResolve()],
                }), */
      resolveExternalsPlugin({
        AMap: "AMap",
      }),
      AutoImport({
        resolvers: [ElementPlusResolver()],
        imports: [
          "vue",
          "vue-router",
          "vue/macros",
          "pinia",
          "@vueuse/head",
          "@vueuse/core",
          {
            "@/hooks/useEcharts": ["useEcharts"],
          },
        ],

        dts: "src/auto-imports.d.ts",
        eslintrc: {
          enabled: false, // Default `false`
          filepath: "./.eslintrc-auto-import.json", // Default `./.eslintrc-auto-import.json`
          globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
        },
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
      Markdown({
        markdownItSetup(md) {
          md.use(MarkdownItAnchor);
        },
      }),
      prismjsPlugin({
        languages: "all", // 语言
        plugins: ["line-numbers", "copy-to-clipboard"],
        theme: "coy", // 主题
        css: true,
      }),
      VueSetupExtend(),
      viteCompression({
        // 开启gzip模式
        verbose: true,
        disable: false,
        threshold: 10240 * 50,
        deleteOriginFile: false, // 压缩后是否删除源文件
        algorithm: "gzip",
        ext: ".gz",
      }),
    ],
    /* css: {
                preprocessorOptions: {
                    scss: {
                        additionalData: '@import "./src/assets/styles/ruoyi.scss";', // 全局公共样式
                    },
                },
            }, */
    resolve: {
      alias: {
        // 设置 `@` 指向 `src` 目录
        "@": path.resolve(__dirname, "./src"),
        "@assets": path.resolve("src/assets"),
        "@comps": path.resolve("src/components"),
        "@utils": path.resolve("src/utils"),
        "@router": path.resolve("src/router"),
        "@store": path.resolve("src/store"),
      },
      //extensions: [".ts", ".js", ".vue", ".json", ".mjs"],
      extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".vue"],
    },
    css: {
      preprocessorOptions: {
        //define global scss variable
        scss: {
          additionalData: `@import "@/assets/style/mixin.scss";`,
        },
      },
      postcss: {
        plugins: [
          // postCssPxToRem({
          //     // 配置在将px转化为rem时 1rem等于多少px(因为我们搭配使用了amfe-flexible插件 此处我们需要设置的值应是UI设计稿全屏基准宽度的十分之一)
          // // 当UI设计稿的全屏基准宽度是1920px时 此处设置的值为192
          // rootValue: 457.6,
          // // 所有px均转化为rem
          // unitPrecision: 5, // 保留到5位小数
          // selectorBlackList: ["ignore"], // 忽略转换正则匹配项
          // propList: ["*", "!border"],
          // replace: true,
          // mediaQuery: false, // 媒体查询( @media screen 之类的)中不生效
          // minPixelValue: 1, //可以选择px小于1的不会被转换
          // }),
          {
            postcssPlugin: "internal:charset-removal",
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === "charset") {
                  atRule.remove();
                }
              },
            },
          },
        ],
      },
    },
    build: {
      // https://blog.csdn.net/lj1530562965/article/details/122231280
      // 混淆器设置
      minify: "terser",
      // 不生成source map文件，默认false
      sourcemap: false,
      // 指定输出路径（相对于项目根目录)，默认dist
      outDir: "dist",
      // 指定生成静态资源的存放路径，默认assets
      assetsDir: "assets",
      // chunk大小警告限制，默认500kbs
      chunkSizeWarningLimit: 1500,
      // 是否禁用css拆分(默认true)，设置false时所有CSS将被提取到一个CSS文件中
      cssCodeSplit: true,
      // 简要配置
      terserOptions: {
        compress: {
          // 移除console
          drop_console: true,
          // 移除debugger
          drop_debugger: true,
        },
        // 保留类名
        keep_classnames: true,
        format: {
          // 移除所有的注释
          comments: false,
        },
      },
      // js、css等文件打包到不同文件夹
      // https://rollupjs.org/guide/en/#outputoptions-object
      /* rollupOptions: {
                    output: {
                        chunkFileNames: "assets/js/[name]-[hash].js",
                        entryFileNames: "assets/js/[name]-[hash].js",
                        assetFileNames: "assets/[ext]/[name]-[hash].[ext]"
                    }
                } */
    },
    server: {
      host: "0.0.0.0", // 默认为localhost
      port: 8081, // 端口号
      open: true, // 是否自动打开浏览器
      proxy: {
        // 本地开发环境通过代理实现跨域，生产环境使用 nginx 转发
        "/dev-api": {
          target: "", // 后端服务实际地址
          changeOrigin: true,
          rewrite: (path) =>
            path.replace(new RegExp("^" + env.VITE_APP_BASE_API), ""),
        },
      },
    },
  };
});
